/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-07
*/
package com.zjmzxfzhl.modules.app.controller;

import com.zjmzxfzhl.common.core.Result;
import com.zjmzxfzhl.common.core.base.BaseController;
import com.zjmzxfzhl.modules.app.entity.AppProj;
import com.zjmzxfzhl.modules.app.form.Chunk;
import com.zjmzxfzhl.modules.app.form.MailInfo;
import com.zjmzxfzhl.modules.app.platform.MailinaboxMailUtils;
import com.zjmzxfzhl.modules.app.platform.MailinaboxUserUtils;
import com.zjmzxfzhl.modules.app.service.AppMptService;
import com.zjmzxfzhl.modules.app.service.AppProjService;
import com.zjmzxfzhl.modules.app.service.AppTaskService;
import com.zjmzxfzhl.modules.app.util.BigFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.mail.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 邮件控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-07
 */
@Slf4j
@RestController
@RequestMapping("/app/mail")
public class AppMailController extends BaseController {
    @Value("${mailinabox.serverHost}")
    private String serverHost;
    @Autowired
    private AppProjService appProjService;
    @Autowired
    private MailinaboxMailUtils mailinaboxMailUtils;
    /**
     * 获取项目邮箱列表
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/list")
    public Result list(@RequestParam String projId,@RequestParam Integer current,@RequestParam Integer size) {
        AppProj appProj = appProjService.queryById(projId);
        if(appProj==null){
            return Result.error("未找到项目");
        }
        List<MailInfo> mailInfos=null;
        try {
            mailInfos= mailinaboxMailUtils.getMail(appProj.getMailbox(),appProj.getMailPassword(),null,null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        if(current<=0){
            return Result.error("请输入正确页码！");
        }
        Map<String, Object> result = new HashMap<>();
        List<MailInfo> reMailInfo = new ArrayList<>();
        int start = (current - 1) * size;
        int end = current * size;
        for (int i = start; i < (mailInfos.size() < end ? mailInfos.size() : end); i++) {
            reMailInfo.add(mailInfos.get(i));
        }
        result.put("current", current);
        result.put("size", size);
        result.put("total", mailInfos.size());
        result.put("mailInfos", reMailInfo);
        return Result.ok(result);
    }

    /**
     * 获取项目邮箱内容详情
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/info")
    public Result info(@RequestParam String projId,@RequestParam Integer orders) {
        AppProj appProj = appProjService.queryById(projId);
        if(appProj==null){
            return Result.error("未找到项目");
        }
        List<MailInfo> mailInfos=null;
        try {
            mailInfos= mailinaboxMailUtils.getMail(appProj.getMailbox(),appProj.getMailPassword(),orders,appProj.getProjId());
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

        return Result.ok(mailInfos);
    }

    /**
     * 获取项目邮箱内容详情
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/annex/{projId}/{orders}/{fileOrders}/{filename}")
    public void annex(@PathVariable String projId,@PathVariable Integer orders,@PathVariable Integer fileOrders,HttpServletResponse response) throws Exception {
        AppProj appProj = appProjService.queryById(projId);
        if(appProj==null){
            return;
        }
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.debug", "true");
            prop.setProperty("mail.store.protocol", "imap");
            prop.setProperty("mail.pop3.host", serverHost);
            prop.setProperty("mail.imap.port", "993");
            prop.setProperty("mail.imap.ssl.enable", "true");
            // 1、创建session
            Session session = Session.getInstance(prop);
            // 2、通过session得到Store对象
            Store store = session.getStore();
            // 3、连上邮件服务器
            store.connect(serverHost,appProj.getMailbox(),appProj.getMailPassword());
            // 4、获得邮箱内的邮件夹
            Folder folder = store.getFolder("inbox");
            folder.open(Folder.READ_ONLY);
            // 获得邮件夹Folder内的所有邮件Message对象
            Message[] messages = folder.getMessages();
            Multipart multipart = (Multipart) messages[orders].getContent();
            BodyPart part = multipart.getBodyPart(fileOrders);
            response.reset();
            response.setContentType(part.getContentType());
            DataInputStream input = new DataInputStream(part.getInputStream());// 得到输入流
            ServletOutputStream output = response.getOutputStream();// 得到输出流
            //输入流转为输出流
            byte[] buf = new byte[4096];
            int length = input.read(buf);
            //保存文件
            while(length != -1){
                output.write(buf, 0, length);
                length = input.read(buf);
            }
            input.close();
            // 5、关闭
            folder.close(false);
            store.close();
            output.close();

        } catch (Exception e) {
            e.getMessage();
        }

    }
}
